package cn.cdzdjd.util;

import java.io.IOException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.druid.support.json.JSONUtils;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.vo.VideoInfoVO;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class KuaiShouSpider {
	public String video_url = "https://www.kuaishou.com/graphql";
	private String query = "query visionVideoDetail($photoId: String, $type: String, $page: String) { visionVideoDetail(photoId: $photoId, type: $type, page: $page) { status type author { id name following headerUrl } photo { id duration caption likeCount realLikeCount coverUrl photoUrl liked timestamp expTag llsid viewCount videoRatio stereoType musicBlocked riskTagContent riskTagUrl manifest { mediaType businessType version adaptationSet { id duration representation {  id  defaultSelect  backupUrl  codecs  url  height  width  avgBitrate  maxBitrate  m3u8Slice  qualityType  qualityLabel  frameRate  featureP2sp  hidden  disableAdaptive } } } manifestH265 photoH265Url coronaCropManifest coronaCropManifestH265 croppedPhotoH265Url croppedPhotoUrl videoResource } tags { type name } commentLimit { canAddComment } llsid danmakuSwitch } } ";

	private RestTemplate restTemplate;

	public VideoInfoVO getVideoInfo(String locationUrl) throws IOException {
		Response response = Jsoup.connect(locationUrl).ignoreContentType(true)
				.userAgent(BrowserConstant.USER_AGENT_PC).header("Accept", BrowserConstant.ACCEPT)
				.referrer(locationUrl).execute();
		Map<String, String> cookies = response.cookies();
		log.error("cookies:{}", cookies);
		URL url = response.url();
		// System.out.println(url);
		String domain = "www.kuaishou.com";
		Map<String, String> params = UrlUtil.convertUrlParamsToMap(url);
		HttpEntity<String> entity = new HttpEntity<>(genBody(params, domain),
				genHeader(params, domain, cookies, url));
		String result = restTemplate.postForObject(video_url, entity, String.class);
		//System.out.println(result);
		return null;

	}

	public HttpHeaders genHeader(Map<String, String> params, String domain, Map<String, String> cookies, URL url) {

		HttpHeaders headers = new HttpHeaders();
		headers.set("content-type", "application/json;charset=UTF-8");
		headers.set("Content-Length", genBody(params, domain).length() + "");
		headers.set("Accept", MediaType.ALL_VALUE);
		headers.set("Origin", "https://" + domain);
		headers.set("Referer", url.toString());
		headers.set("User-Agent", BrowserConstant.USER_AGENT_PC);
		headers.set("Host", domain);
		StringBuffer buffer = new StringBuffer();
		buffer.append("kpf=").append(cookies.get("kpf")).append(";")
		.append(" clientid=").append(cookies.get("clientid")).append(";")
		.append(" did=").append(cookies.get("did")).append(";")
		.append(" didv=").append(cookies.get("didv")).append(";")
		.append(" kpn=").append(cookies.get("kpn"));
		log.error("cookie:{}", buffer);
		//kpf=PC_WEB; clientid=3; did=web_b6de4e6e6d16560de88dcf43750cd35f; didv=1716133670000; kpn=KUAISHOU_VISION
		headers.set("Cookie", buffer.toString());
		return headers;
	}

	public String genBody(Map<String, String> params, String domain) {
		Map<String, Object> requestBody = new LinkedHashMap<>();
		requestBody.put("operationName", "visionVideoDetail");
		requestBody.put("fid", params.get("fid"));
		JSONObject variables = new JSONObject();
		variables.put("photoId", params.get("photoId"));
		variables.put("page", "detail");
		requestBody.put("variables", variables.toString());
		requestBody.put("query", query);

		String body = JSONUtils.toJSONString(requestBody);
		return body;
	}

}
